import { Suspense } from 'react';
import WishGraphWrapper from '@/components/WishGraphWrapper';
import { query } from '@/lib/database';
import { RowDataPacket } from 'mysql2';

// Server Component to fetch initial data
async function getInitialWishId() {
  // Try to find a wish that has connections (is desired and has matches)
  // Or just the latest desired wish.
  try {
    const rows = (await query(
      "SELECT id FROM wishes WHERE type = 'desired' ORDER BY created_at DESC LIMIT 1"
    )) as RowDataPacket[];
    return rows.length > 0 ? rows[0].id : 1; // Default to 1 if no wishes
  } catch (e) {
    console.error("Failed to fetch initial wish:", e);
    return 1;
  }
}

export default async function Home() {
  const initialWishId = await getInitialWishId();

  return (
    <main className="relative w-full h-screen overflow-hidden bg-paper text-ink-black font-serif selection:bg-seal-red selection:text-white">
      {/* Background Texture Overlay - using CSS global instead */}
      <div className="absolute inset-0 pointer-events-none opacity-10 mix-blend-multiply z-50"></div>

      {/* Header / Title */}
      <header className="absolute top-0 left-0 w-full p-6 z-20 flex justify-between items-start pointer-events-none">
        <div>
          <h1 className="text-5xl font-bold tracking-widest text-ink-black drop-shadow-sm" style={{ writingMode: 'vertical-rl', textOrientation: 'upright' }}>
            愿望
          </h1>
          <h2 className="text-2xl mt-4 text-ink-medium tracking-widest" style={{ writingMode: 'vertical-rl', textOrientation: 'upright' }}>
            共鸣
          </h2>
        </div>

        <div className="pointer-events-auto flex flex-col gap-4 items-end">
          <div className="flex gap-4">
            <a href="/login" className="px-6 py-2 border border-ink-medium rounded-full hover:bg-ink-black hover:text-paper transition-all duration-500">
              入梦
            </a>
            <a href="/register" className="px-6 py-2 bg-seal-red text-white rounded-full hover:bg-red-800 transition-all duration-500 shadow-lg shadow-red-900/20">
              许愿
            </a>
          </div>
        </div>
      </header>

      {/* Main Graph Area */}
      <div className="absolute inset-0 z-0">
        <Suspense fallback={<div className="flex items-center justify-center h-full text-ink-light animate-pulse">墨迹晕染中...</div>}>
          <WishGraphWrapper initialCenterId={initialWishId} />
        </Suspense>
      </div>

      {/* Footer / Quote */}
      <footer className="absolute bottom-6 right-6 z-20 pointer-events-none text-right">
        <p className="text-ink-medium text-sm italic">
          "念念不忘，必有回响"
        </p>
      </footer>
    </main>
  );
}